import { Button, Modal, Typography, message } from "antd";
import React, { useRef, useState } from "react";
// @ts-ignore
import SignatureCanvas from "react-signature-canvas";
export type SignWriteModalProps = {
	onCancel: (flag?: boolean) => void;
	onOk: (values: string) => Promise<boolean>;
	open: boolean;
};
const SignWriteModal: React.FC<SignWriteModalProps> = ({ onOk = () => {}, onCancel = () => {}, open = false }) => {
	const signAtureRef = useRef();
	const [showInstruction, setShowInstruction] = useState(true);
	const [loading, setLoading] = useState<any>(false);
	const handleCancel = () => {
		onCancel(false);
		// @ts-ignore
		signAtureRef?.current?.clear();
		setShowInstruction(true);
	};
	const handleOk = async () => {
		// @ts-ignore
		if (signAtureRef?.current?.isEmpty()) {
			message.error("签名不能为空");
			return;
		}
		setLoading(true);
		// @ts-ignore
		const isSuccess = await onOk(signAtureRef?.current?.toDataURL());
		setLoading(false);
		if (isSuccess) {
			// @ts-ignore
			// signAtureRef?.current?.clear();
			// setShowInstruction(true);
			handleCancel();
		}
	};

	const onClear = () => {
		// @ts-ignore
		signAtureRef?.current?.clear();
		setShowInstruction(true);
	};

	const onBeginSigning = () => {
		setShowInstruction(false);
	};

	return (
		<>
			<Modal
				width="800px"
				title="请签名"
				open={open}
				onOk={handleOk}
				onCancel={handleCancel}
				footer={[
					<Button key="reset" onClick={onClear}>
						清空
					</Button>,
					<Button key="back" onClick={handleCancel}>
						取消
					</Button>,
					<Button loading={loading} key="ok" type="primary" onClick={handleOk}>
						保存
					</Button>
				]}
			>
				<div style={{ position: "relative" }}>
					<SignatureCanvas
						ref={signAtureRef}
						penColor="black"
						minWidth={2}
						maxWidth={3}
						velocityFilterWeight={1}
						backgroundColor="#f7f7f7"
						canvasProps={{
							width: "751px",
							height: 300,
							className: "sigCanvas",
							onMouseDown: onBeginSigning
						}}
					/>
					{showInstruction && (
						<div
							style={{
								position: "absolute",
								top: "50%",
								left: "50%",
								transform: "translate(-50%, -50%)"
							}}
						>
							<Typography>使用鼠标在此签名</Typography>
						</div>
					)}
				</div>
			</Modal>
		</>
	);
};

export default SignWriteModal;
